import type { FormInstance } from 'ant-design-vue'
import type { SelectValue } from 'ant-design-vue/es/select'
import { createApp, getTenantList } from '@/apis/app-manage'
import { Button, Drawer, Form, FormItem, Input, message, Select, Space, Textarea } from 'ant-design-vue'

export default defineComponent({
  emits: ['success'],
  setup(_, { expose, emit }) {
    const open = ref(false)
    const loading = ref(false)
    const formRef = useTemplateRef<FormInstance>('formRef')
    const formState = reactive<{
      tenantId: SelectValue
      appName: string
      appDesc?: string
    }>({
      tenantId: undefined,
      appName: '',
      appDesc: '',
    })
    const rules = {
      tenantId: [{ required: true, message: '请选择所属租户' }],
      appName: [{ required: true, message: '请输入应用名称' }],
    }
    const companyList = ref<any[]>([])
    async function onSubmit() {
      try {
        await formRef.value?.validate()
        loading.value = true
        const res = await createApp(formState)
        if (res.status === 0) {
          message.success('创建成功')
          open.value = false
          emit('success')
        }
        else {
          message.error(res.msg)
        }
      }
      finally {
        loading.value = false
      }
    }
    expose({
      open() {
        open.value = true
      },
    })
    onMounted(async () => {
      const res = await getTenantList()
      companyList.value = res.data.options
    })
    return () => (
      <Drawer open={open.value} width="40%" title="添加应用" onClose={() => (open.value = false)}>
        <Form ref="formRef" labelCol={{ span: 3 }} model={formState} rules={rules}>
          <FormItem label="所属租户" name="tenantId">
            <Select value={formState.tenantId} onUpdate:value={value => (formState.tenantId = value)} placeholder="请选择所属租户" options={companyList.value} />
          </FormItem>
          <FormItem label="应用名称" name="appName">
            <Input value={formState.appName} onUpdate:value={value => (formState.appName = value)} placeholder="请输入应用名称" />
          </FormItem>
          <FormItem label="应用描述" name="appDesc">
            <Textarea value={formState.appDesc} onUpdate:value={value => (formState.appDesc = value as string)} rows={4} placeholder="请输入应用描述" />
          </FormItem>
          <FormItem wrapperCol={{ span: 18, offset: 4 }}>
            <Space class="w-full flex justify-end">
              <Button onClick={() => open.value = false}>
                取消
              </Button>
              <Button loading={loading.value} type="primary" onClick={onSubmit}>
                提交
              </Button>
            </Space>
          </FormItem>
        </Form>
      </Drawer>
    )
  },
})
